package com.meterreadingsys.httpserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class UploadHttpClient {
    
	/**
	 * �ύ���������ļ������
	 * 
	 * @param url
	 *            ��������ַ
	 * @param param
	 *            ����
	 * @return ���������ؽ��
	 * @throws Exception
	 */
	public static String uploadSubmit(String url, Map<String, String> param,
			File file) throws Exception {
		HttpPost post = new HttpPost(url);
        HttpClient httpclient=new DefaultHttpClient();
		MultipartEntity entity = new MultipartEntity();
	
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
			}
		}
		// ����ļ�����
		if (file != null && file.exists()) {
			entity.addPart("image", new FileBody(file));
			
		}
		post.setEntity(entity);
		HttpResponse response = httpclient.execute(post);
		
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK) {
			HttpEntity result = response.getEntity();
			if (result != null) {
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		return sb.toString();
	}}
